﻿using System;
using System.Linq;
using System.Reflection;

namespace Purdue.Helper
{
    public static class EnumAttributeHelper
    {
        /// <summary>
        /// Get the first attribute of the given attribute type from an enums field.
        /// </summary>
        /// <typeparam name="T">The type of the attribute to retrieve.</typeparam>
        /// <param name="value">The enum field to get the attribute from.</param>
        /// <param name="attribute">The attribute returned.</param>
        /// <returns>True if the attribute was found.</returns>
        public static bool TryGetAttribute<T>(object value, out T attribute) where T : class
        {
            attribute = null;

            if (value != null)
            {
                string valueString = value.ToString();
                FieldInfo fieldInfo = value.GetType().GetField(valueString);
                if (fieldInfo != null)
                {
                    attribute = fieldInfo.GetCustomAttributes(typeof(T), false).OfType<T>().FirstOrDefault();
                }
            }

            return (attribute != null);
        }
    }

    /// <summary>
    /// A generic attribute, useful to attach a single key to an arbitrary object. 
    /// </summary>
    [AttributeUsage(AttributeTargets.All, AllowMultiple = false, Inherited = true)]
    public sealed class GenericAttribute : Attribute
    {
        public GenericAttribute(object value)
        {
            this.Value = value;
        }

        public object Value { get; private set; }
    }

    /// <summary>
    /// A generic attribute, useful to attach a single key to an arbitrary object. 
    /// </summary>
    [AttributeUsage(AttributeTargets.All, AllowMultiple = false, Inherited = true)]
    public sealed class PlatformAttribute : Attribute
    {
        public PlatformAttribute(object value)
        {
            this.Value = value;
        }

        public object Value { get; private set; }
    }
}
